package com.source3g.dubbo.registry.consul;

import com.alibaba.dubbo.common.URL;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Created by jianglin on 2016/12/27
 */
public class HasingIdGenerator implements ServiceIdGenerator {

    public static final HasingIdGenerator hasingIdGenerator = new HasingIdGenerator();

    private static final char[] HEX_CHARS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
            'a', 'b', 'c', 'd', 'e', 'f'};

    private HasingIdGenerator() {
    }

    public String generateId(String path) {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-1");
            byte[] bytes = digest.digest(path.getBytes(StandardCharsets.UTF_8));
            return new String(encodeHex(bytes, 0, 8));
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalStateException(e);
        }
    }

    private char[] encodeHex(byte[] bytes, int offset, int length) {
        char chars[] = new char[length];
        for (int i = 0; i < length; i = i + 2) {
            byte b = bytes[offset + (i / 2)];
            chars[i] = HEX_CHARS[(b >>> 0x4) & 0xf];
            chars[i + 1] = HEX_CHARS[b & 0xf];
        }
        return chars;
    }

    @Override
    public String generate(URL url) {
        if (url == null) {
            return null;
        }

        return generateId(url.getHost() + "-" + url.getPort() + "-" + url.getPath());
    }
}
